package admin

import (
	"crypto/md5"
	"encoding/hex"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/admin"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	requestData := struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}{}
	c.ShouldBindJSON(&requestData)

	var adminStruct admin.AdminStruct
	exists, err := model.GetModelDataFirst(model.Db,
		adminStruct.TableName(),
		&adminStruct,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"username": requestData.Username,
			},
		})
	if !exists {
		controller.Fail(c, "用户名不存在")
		return
	}

	if err != nil {
		controller.Fail(c, "登录失败"+err.Error())
		return
	}

	if adminStruct.Status != 1 {
		controller.Fail(c, "账号已禁用,请联系管理员")
		return
	}

	data := []byte(requestData.Password + "|" + adminStruct.Salt)
	hash := md5.Sum(data)
	hashString := hex.EncodeToString(hash[:])
	//密码校验
	if hashString != adminStruct.Password {
		controller.Fail(c, "登录失败")
		return
	}

	//刷新token
	var adminTokenStruct admin.AdminTokenStruct
	accessToken, refreshToken, expires := adminTokenStruct.UpdateAccessToken(adminStruct.Id)

	controller.Success(c, map[string]interface{}{
		"username":     requestData.Username,
		"roles":        []string{requestData.Username},
		"accessToken":  accessToken,
		"refreshToken": refreshToken,
		"expires":      expires,
	})

}
